package cn.licoy.wdog.core.controller.hospital;

import cn.licoy.wdog.common.annotation.SysLogs;
import cn.licoy.wdog.common.bean.ResponseCode;
import cn.licoy.wdog.common.bean.ResponseResult;
import cn.licoy.wdog.common.exception.RequestException;
import cn.licoy.wdog.core.dto.hospitalUser.AppversionDto;
import cn.licoy.wdog.core.dto.hospitalUser.PageUtileDto;
import cn.licoy.wdog.core.dto.system.resource.ResourceDTO;
import cn.licoy.wdog.core.entity.hospital.AppVersion;
import cn.licoy.wdog.core.entity.system.SysRole;
import cn.licoy.wdog.core.service.hospital.AppVersionService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Random;

/**
 * @author Sunne
 * Create time 2018/6/26 17:33
 * @return null
 **/
@RestController
@RequestMapping(value = "/appversion")
@Api(tags = {"第一期--app版本操作"})
public class AppVersionController {
    @Autowired
    AppVersionService appVersionService;


    @PostMapping(value = {"/add"})
    @ApiOperation(value = "app上传新版本文件")
    public ResponseResult<AppversionDto> verificationCode(@RequestBody @Validated  @RequestParam("file") MultipartFile file,
                                           HttpServletRequest request) {
        String contentType = file.getContentType();

        Random r=new Random();
        int rcode = r.nextInt(900000)+100000;
        String originalName = file.getOriginalFilename();
        Long fileSize = file.getSize();
        String filename = originalName.substring(originalName.lastIndexOf("\\")+1);
        //后缀名
        String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
        if (!"apk".equals(fileExtName)){
            return ResponseResult.e(ResponseCode.FAIL);
        }
        filename = rcode+"."+fileExtName;
        AppversionDto dto = new AppversionDto();
        dto.setFileName(filename);
        dto.setFileSize(String.valueOf(fileSize));
        String filePath = "E:/project/emp-hospital/app/";
        try {
            this.uploadFile(file.getBytes(), filePath, filename);
            return ResponseResult.e(ResponseCode.OK,dto);
        } catch (Exception e) {
            throw RequestException.fail("app上传失败");
        }

    }


    @PostMapping(value = {"/saveversioninfo"})
    @ApiOperation(value = "app保存新版本信息")
    @SysLogs("app保存新版本信息")
    public ResponseResult appVersionSave(@RequestBody @Validated @ApiParam("app版本信息") AppversionDto dto) {
        appVersionService.save(dto);
        return ResponseResult.e(ResponseCode.OK,"操作成功");
    }
    @PostMapping(value = {"/selectall"})
    @ApiOperation(value = "查看所有版本信息")
    @SysLogs("查看所有版本信息")
    @ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
    public ResponseResult selectAll(@RequestBody @Validated @ApiParam("分页信息") PageUtileDto dto){
        Page<AppVersion> appVersionPage = appVersionService.selectAll(dto);
        return ResponseResult.e(ResponseCode.OK,appVersionPage);
    }

    @PostMapping(value = {"/latestversion"})
    @ApiOperation(value = "查找最新版本")
    @SysLogs("查找最新版本")
    public ResponseResult add(){
        AppVersion app = appVersionService.latestversion();
        return ResponseResult.e(ResponseCode.OK,app);
    }


    @RequestMapping(value = "/download")
    @ApiOperation(value = "app下载")
    public ResponseResult download(@RequestParam("filename")String filename,HttpServletResponse response) {
        String filePath = "E:/project/emp-hospital/app";
        File file = new File(filePath + "/" + filename);
        if (file.exists()) { //判断文件父目录是否存在
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            try {
                //设置响应头，控制浏览器下载该文件
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                //缓存文件流
                FileInputStream in = new FileInputStream("E:/project/emp-hospital/app/" + filename);
                OutputStream out = response.getOutputStream();
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                //循环将输入流中的内容读取到缓冲区当中ss
                while ((len = in.read(buffer)) > 0) {
                    //输出缓冲区的内容到浏览器，实现文件下载
                    out.write(buffer, 0, len);
                }
                //关闭文件输入流
                in.close();
                //关闭输出流
                out.close();
            } catch (Exception e) {
                return ResponseResult.e(ResponseCode.FAIL, "文件下载出错");
            }

            return ResponseResult.e(ResponseCode.OK, "文件下载操作成功");
        }else {
            return ResponseResult.e(ResponseCode.FAIL, "文件不存在");
        }
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
